package org.tof.hotel.entity;

import org.apache.log4j.Logger;
import org.tof.hotel.entity.Booking;
import org.tof.hotel.RoomLevel;
import org.tof.hotel.csv.CSVParser;
import org.tof.hotel.csv.CSVWriter;

import java.util.ArrayList;
import java.util.Random;

/**
 * Class which corresponds to the hotel room
 */
public class Room extends BaseForRoom {
    public Room(int beds, RoomLevel roomLevel) {
        super(beds, roomLevel);
        hotelRooms.add(this);
        logger.debug("generated object of class \"Room\"");
    }

    static Logger logger = Logger.getLogger(Room.class.getName());
    private static ArrayList<Room> hotelRooms = new ArrayList<Room>();

    /**
     * Find  room which meets requirements specified in application form
     *
     * @param application Application for which application room should be found
     * @return <code>Room</code> available room which meets specified requirements; if no such room - returns <code>null</code>
     */
    public static Room findRoom(Application application) {
        for (Room room : hotelRooms) {
            if (Booking.isNotBooked(room, application.getBeginDate(), application.getEndDate()) &&
                    (room.getBeds() == application.getBeds()) &&
                    (room.getRoomLevel() == application.getRoomLevel())) {
                return room;
            }
        }
        return null;
    }

    // ----- GeneratoR ----- //

    @Override
    public void generate(int num) {
        logger.debug("generating " + num + " objects of class \"Room\"");
        int r1 = (new Random()).nextInt(4);
        int r2 = (new Random()).nextInt(4);
        RoomLevel roomLevel = (RoomLevel.values())[r2];
        for (int i = 1; i <= num; i++) {
            new Room(r1, roomLevel);
        }
    }
    // ----- CSVGenerable-generator ----- //

    @Override
    public ArrayList<String> getFields() {
        ArrayList<String> list = new ArrayList<String>();
        ArrayList<String> tmp = new ArrayList<String>();
        for (Room r : hotelRooms) {
            tmp.clear();
            tmp.add(r.getId().toString());
            tmp.add(String.valueOf(r.getBeds()));
            tmp.add(r.getRoomLevel().toString());
            list.add(CSVWriter.getInstance().FieldsToCSVString(tmp));
        }
        return list;
    }

    @Override
    public ArrayList<Class> createInstancesFromCsvFile(String filename) {
        CSVParser parser = new CSVParser();
        ArrayList<String[]> list = new ArrayList<String[]>(parser.parse(filename));
        ArrayList<Class> generated = new ArrayList<Class>();
        for(int i=1; i < list.size() ;i++){
            generated.add(new Room(Integer.decode(list.get(i)[1]),RoomLevel.valueOf(list.get(i)[2])).getClass());    
        }
        return generated;
    }

}
